package com.charm.restaurant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.charm.restaurant.common.Result;
import com.charm.restaurant.entity.Dish;
import com.charm.restaurant.mapper.DishMapper;
import com.charm.restaurant.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 菜品服务实现类
 */
@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    /**
     * 新增菜品
     */
    @Override
    @Transactional
    public Result<Dish> saveDish(Dish dish) {
        this.save(dish);
        return Result.success(dish);
    }

    /**
     * 分页查询菜品
     */
    @Override
    public Result<Page<Dish>> pageDish(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        
        this.page(pageInfo, queryWrapper);
        
        return Result.success(pageInfo);
    }

    /**
     * 根据ID查询菜品
     */
    @Override
    public Result<Dish> getDishById(Long id) {
        Dish dish = this.getById(id);
        return Result.success(dish);
    }

    /**
     * 修改菜品
     */
    @Override
    @Transactional
    public Result<Dish> updateDish(Dish dish) {
        this.updateById(dish);
        return Result.success(dish);
    }

    /**
     * 删除菜品
     */
    @Override
    @Transactional
    public Result<String> deleteDish(List<Long> ids) {
        this.removeByIds(ids);
        return Result.success("删除菜品成功");
    }

    /**
     * 修改菜品状态
     */
    @Override
    @Transactional
    public Result<String> updateStatus(Integer status, List<Long> ids) {
        // 批量更新菜品状态
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);
        
        Dish dish = new Dish();
        dish.setStatus(status);
        
        this.update(dish, queryWrapper);
        
        return Result.success("菜品状态修改成功");
    }

    /**
     * 查询所有在售菜品
     */
    @Override
    public Result<List<Dish>> listDish(Dish dish) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 查询状态为1的菜品（在售）
        queryWrapper.eq(Dish::getStatus, 1);
        
        // 按照更新时间降序排序
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        
        List<Dish> list = this.list(queryWrapper);
        
        return Result.success(list);
    }
} 